#coding=utf-8 


"""
安装 pexpect 模块  
Unix 或者 linux



 


"""

"""
 
先安装   setuptools-0.6c10.win32-py2.6.exe
先安装   pywin32




安装 winpexpect 模块  
windows下支持

http://pypi.python.org/packages/source/w/winpexpect/ 下载



 

cd  /d    D:\TEMP\winpexpect-1.3
D:\Python26\python.exe   setup.py  install


？   ImportError: No module named setuptools
！   安装 setuptools 拷贝 Lib到python的安装目录


    
D:\Python26\python.exe  E:\py_dev\ssh_pexpect.py


telnet 60.190.25.91  2223
login:

"""



import sys

"""
try:
    import pexpect
except pexpect.EOF:
    import winpexpect as pexpect
"""
import winpexpect  
# python 3.2
import pty

def test():
    #exp = winpexpect.winspawn('D:/cygwin/bin/dir.exe' )
    c = winpexpect.spawn('D:/cygwin/bin/dir.exe')
    #txt = '[Tt]elnet'
    #c.expect(txt)
    sys.exit()


test()

# 执行函数
def exp_cmd(ip, port,user, passwd, cmd):
    exp = pexpect.spawn('telnet %s %s  ' % (ip, port))
    r = ''
    try:
        i = exp.expect(['login:', 'continue connecting (yes/no)?'])
        if i == 0 :
            exp.sendline(passwd)
        elif i == 1:
            exp.sendline('yes')
    except pexpect.EOF:
        exp.close()
    else:
        r = exp.read()
        exp.expect(pexpect.EOF)
        exp.close()
    return r




hosts = """
192.168.0.120:2223:root:oracle:uptime,df
"""

for host in hosts.split("\n"):
    if host:
        ip,port,user, passwd, cmds = host.split(":")
        for cmd in cmds.split(","):
            print "-- %s run:%s --" % (ip, cmd)
            print exp_cmd(ip, port,user, passwd, cmd)                                


